package com.example.mybatisplus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.mybatisplus.common.JsonResponse;
import com.example.mybatisplus.model.domain.User;
import com.example.mybatisplus.mapper.UserMapper;
import com.example.mybatisplus.model.dto.PageDto;
import com.example.mybatisplus.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lxp
 * @since 2021-12-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(User::getUsername, user.getUsername()).eq(User::getPassword, user.getPassword());
        User one = userMapper.selectOne(wrapper);
        return one;
    }

    @Override
    public JsonResponse regist(@RequestBody User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(User::getUsername, user.getUsername());
        User one = userMapper.selectOne(wrapper);
        if (one == null) {
            //注册用户不存在，可以直接注册
            System.out.println(user);
            userMapper.insert(user);
            System.out.println(user);
            return JsonResponse.success(true, "执行成功");
        }
        return JsonResponse.success(false, "该用户已存在");
    }

    @Override
    public Page<User> listByPage(PageDto page, User user) {
        Page<User> page1 = new Page<>(page.getPageNo(), page.getPageSize());
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (user.getUsername() != null) {
            wrapper.lambda().like(User::getUsername, user.getUsername());
        }
        if (user.getUserType() != null) {
            wrapper.lambda().like(User::getUserType, user.getUserType());
        }
        page1 = userMapper.selectPage(page1, wrapper);
        return page1;
    }
}
